﻿#region License

// Another free, open solution by someone who gets it.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Reflection;

using Patterns.Text;

namespace Patterns.Reflection
{
	///<summary>
	///	Provides a default implementation of the <see cref = "IClassMatcher" /> contract.
	///</summary>
	public class ClassMatcher : NamespaceMatcher, IClassMatcher
	{
		#region IClassMatcher Members

		///<summary>
		///	Determines whether the provided member matches this instance's filter criteria.
		///</summary>
		///<param name = "info">The member information.</param>
		///<returns>True if this instance's filter criteria matches the provided member information; otherwise, false.</returns>
		public override bool IsMatch(MemberInfo info)
		{
			string className = GetClassName(info);
			return base.IsMatch(info) && IsInclusionMatch(ClassIncludePattern, className) && IsExclusionMatch(ClassExcludePattern, className);
		}

		///<summary>
		///	Gets or sets the inclusion pattern.
		///</summary>
		public CompiledRegex ClassIncludePattern{ get; set; }

		///<summary>
		///	Gets or sets the exclusion pattern.
		///</summary>
		public CompiledRegex ClassExcludePattern{ get; set; }

		#endregion

		/// <summary>
		/// 	Gets the name of the class represented by the system member information.
		/// </summary>
		/// <param name = "info">The system member information.</param>
		/// <returns>The class name.</returns>
		/// <exception cref = "InvalidOperationException">Thrown if the <paramref name = "info" /> parameter is not a type, or does not provide declaring type information.</exception>
		protected virtual string GetClassName(MemberInfo info)
		{
			var type = info as Type;

			if (type != null) return type.AssemblyQualifiedName;

			if (info.DeclaringType == null) throw new InvalidOperationException(string.Format("Could not determine class name from MemberInfo: {0}", info));

			return info.DeclaringType.AssemblyQualifiedName;
		}
	}
}